package com.fjut.kms.controller;

import com.fjut.kms.domain.User;
import com.fjut.kms.domain.UserLicense;
import com.fjut.kms.exception.KMSException;
import com.fjut.kms.service.*;
import com.fjut.kms.tools.RsaKey;
import com.fjut.kms.tools.TimeHelper;
import com.fjut.kms.tools.XmlManager;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Empathy on 2017/7/31.
 * MODIFIED by nzx 2017/8/19
 */
@WebServlet(name = "SecurityKMSServlet")
public class SecurityKMSServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        BufferedReader brReq = request.getReader();
        StringBuffer sResult = new StringBuffer();
        String line = null;
        //char buf[] = new char[300];
        try{
            String xmlStr;
            while ((line = brReq.readLine())!=null){
                sResult.append(line)
                        .append("\n");
            }
            xmlStr=sResult.toString();
            if(xmlStr == null||xmlStr.trim().equals(""))return;

            //HttpSession session=request.getSession();
            RsaKey key = new RsaKey();
            xmlStr = xmlStr.replace("\r","").replace("\n","");
            xmlStr = key.decrypt2(xmlStr);//RSA解密
            xmlStr = java.net.URLDecoder.decode(xmlStr ,"UTF-8");  // 避免中文乱码

            String command = XmlManager.GetFirtElemntByTagName("cmdType",xmlStr);
            if("login".equals(command)){

                String username = XmlManager.GetFirtElemntByTagName("userName",xmlStr);
                String pass = XmlManager.GetFirtElemntByTagName("password",xmlStr);
                UserService userService = new UserServiceImpl();
                UserLicenseService ulService =new UserLicenseServiceImpl();
                User user = null;
                List<UserLicense> ulList= new ArrayList<>();
               // try{
                    user = userService.checkUser(username,pass);
                    user.setMachineId(XmlManager.GetFirtElemntByTagName("machineId",xmlStr));
                    user.setMac(XmlManager.GetFirtElemntByTagName("mac",xmlStr));
                    user.setLoginDate(TimeHelper.getNowTime());
                    user.setIp(request.getRemoteAddr().toString());
                    userService.addLoginRecord(user);
                    ulList=ulService.getUserLicense(username);
                    List<Object> list=new ArrayList<>();
                    for (int i=0;i<ulList.size();i++){
                        list.add(ulList.get(i));
                    }
                    String req=XMLService.generateXMLContents(list,"com.fjut.kms.domain.UserLicense");
                    request.getSession().setAttribute("loginedUser",user);
                    //response.sendRedirect("/test.jsp");//重定向test.jsp
                    //String req=XmlManager.buildLoginResultXml();
                    System.out.println(req);
                    response.getWriter().write(req);
                    System.out.println(username+"User Loging!");
              //  }
              //  catch (KMSException e){
              //      String errorMessage=XmlManager.buildXmlError(e.getMessage().toString());
              //      response.getWriter().write(errorMessage);
              //      request.setAttribute("errMsg",e.getMessage());
               // }
            }else if ("loginCheck".equals(command)){
                String username = XmlManager.GetFirtElemntByTagName("userName",xmlStr);
                String pass = XmlManager.GetFirtElemntByTagName("password",xmlStr);
                UserService userService = new UserServiceImpl();
                userService.checkUser(username,pass);
                response.getWriter().write("success");
            } else if ("register".equals((command))){
                UserService userService =new UserServiceImpl();
                User user=new User();
                user.setUserName(XmlManager.GetFirtElemntByTagName("userName",xmlStr));
                user.setUserPass(XmlManager.GetFirtElemntByTagName("password",xmlStr));
                user.setCnName(XmlManager.GetFirtElemntByTagName("cnName",xmlStr));
                user.setCategory(XmlManager.GetFirtElemntByTagName("category",xmlStr));
                user.setDepyName(XmlManager.GetFirtElemntByTagName("deptName",xmlStr));
                user.setEmail(XmlManager.GetFirtElemntByTagName("email",xmlStr));
                user.setRegTime(TimeHelper.getNowTime());
                userService.isRegister(user);
                response.getWriter().write("注册成功！");
            }else if("getRegisterMessage".equals(command)){
                DepartmentService deptService=new DepartmentServiceImpl();
                ParametersService paraService=new ParametersServiceImpl();
                StringBuffer resultSB=new StringBuffer();
                String retStr=deptService.getDeptListStr();
                retStr=retStr+";"+paraService.getParaList("用户类型");
             //   if(deptService.getDeptListStr()!=null) resultSB.append(deptService.getDeptListStr()).append(";");
              //  if(paraService.getParaList("userType")!=null) resultSB.append(paraService.getParaList("userType")).append(";");
                response.getWriter().write(retStr);
            }else if("ModifyPassword".equals(command)){
                UserService userService=new UserServiceImpl();
                userService.modifyPassword(XmlManager.GetFirtElemntByTagName("userName",xmlStr),XmlManager.GetFirtElemntByTagName("oldPass",xmlStr),XmlManager.GetFirtElemntByTagName("newPass",xmlStr));
                response.getWriter().write("更改成功！");
            }
        }catch (KMSException kms){
            String result=XMLService.generateXMLerror(kms.getMessage());
            response.getWriter().write(result);
            System.out.print(kms.getMessage());
        }
        catch (Exception ex){
        	 String result=XMLService.generateXMLerror(ex.getMessage());
             response.getWriter().write(result);
             System.out.println(ex.getMessage());
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
